package config

import (
	"common/helper"
	"golang.org/x/net/context"
	"time"
)

const Def_Var = "1"

// 订阅行为
func InitSubRedis() {
	if nil == CfgRedis {
		helper.InfoLog("InitSubRedis error, redis ptr nil ")
		return
	}

	go subRedisGet()

}

func subRedis() {
	ctx := context.Background()
	pubSub := CfgRedis.PSubscribe(ctx, "__keyevent@*__:set")

	defer func() {
		helper.InfoLog("subRedis error, return")
		pubSub.Close()
	}()

	for {
		msg, err := pubSub.ReceiveMessage(ctx)
		if err != nil {
			helper.InfoLog("Error receiving message: %s", err)
			break
		}

		helper.InfoLog("Received message: %s %s\n", msg.Channel, msg.Payload)

		LoadAllCfg()
	}
}

func subRedisGet() {

	var cfgVersion string

	//多个服同时开
	cfgVersion, _ = CfgRedis.Get(context.Background(), "cfg_version").Result()
	if len(cfgVersion) == 0 {
		CfgRedis.Set(context.Background(), "cfg_version", Def_Var, 0)
		cfgVersion = Def_Var
	}

	for {
		time.Sleep(1 * time.Second)

		newCfgVersion, err := CfgRedis.Get(context.Background(), "cfg_version").Result()
		if nil != err {
			continue
		}

		if newCfgVersion == cfgVersion {
			continue
		}
		cfgVersion = newCfgVersion

		LoadAllCfg()
	}

}
